package com.seasonsfood.mall.web.dispatch.controller.dispatch;


import com.alibaba.dubbo.config.annotation.Reference;
import com.seasonsfood.mall.service.dispatch.api.domain.DispSiteUnit;
import com.seasonsfood.mall.service.dispatch.api.service.DispSiteUnitService;
import com.seasonsfood.mall.util.constant.ResponseCode;
import com.seasonsfood.mall.util.exception.BizException;
import com.seasonsfood.mall.util.model.JsonResponse;
import com.seasonsfood.mall.util.util.Assert;
import com.seasonsfood.mall.util.util.ResponseUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@RestController
@RequestMapping("dispSiteUnit")
public class DispSiteUnitController {
    @Reference(check = false)
    DispSiteUnitService dispSiteUnitService;


    @RequestMapping("siteUnitList")
    public JsonResponse siteUnitList(Long parentId, Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        Assert.notNull(parentId);
        return ResponseUtils.setSuccess(dispSiteUnitService.siteUnitList(parentId, pageNum, pageSize));
    }

    @RequestMapping("addSiteUnit")
    public JsonResponse addSiteUnit(DispSiteUnit dispSiteUnit) {

        Assert.hasText(dispSiteUnit.getSiteUnitName(), "地点单元名称不能为空");
        Assert.notNull(dispSiteUnit.getParentSiteId(), "请选择上级地址");
        try {
            ResponseCode responseCode = dispSiteUnitService.addSiteUnit(dispSiteUnit);
            if (!ResponseCode.SUCCESS.equals(responseCode)) {
                throw new BizException(responseCode);
            }
            return ResponseUtils.setSuccess();
        } catch (BizException e) {
            return ResponseUtils.setToJson(e.getResponseCode());
        } catch (IllegalArgumentException e) {
            return ResponseUtils.setJsonAndMsg(ResponseCode.NOT_NULL, e.getMessage(), true);
        }
    }

    //启用禁用/修改名称
    @RequestMapping("updateSiteUnit")
    public JsonResponse updateSiteUnit(DispSiteUnit dispSiteUnit) {
        Assert.notNull(dispSiteUnit.getId());
        try {
            ResponseCode responseCode = dispSiteUnitService.updateSiteUnit(dispSiteUnit);
            if (!ResponseCode.SUCCESS.equals(responseCode)) {
                throw new BizException(responseCode);
            }
            return ResponseUtils.setSuccess();
        } catch (BizException e) {
            return ResponseUtils.setToJson(e.getResponseCode());
        } catch (IllegalArgumentException e) {
            return ResponseUtils.setJsonAndMsg(ResponseCode.NOT_NULL, e.getMessage(), true);
        }
    }

}
